package com.crm.common.utils;

import java.security.SecureRandom;
import java.util.Random;

public class RandomStringGenerator {

    private static final String DIGITS = "0123456789";
    private static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
    
    private static final Random random = new SecureRandom();

    /**
     * 生成包含数字和大小写字母的随机字符串
     * @param length 字符串长度
     * @return 随机字符串
     */
    public static String generate(int length) {
        return generate(length, true, true, true);
    }

    /**
     * 生成包含数字和大写字母的随机字符串
     * @param length 字符串长度
     * @return 随机字符串
     */
    public static String generateUppercase(int length) {
        return generate(length, true, true, false);
    }

    /**
     * 生成包含数字和小写字母的随机字符串
     * @param length 字符串长度
     * @return 随机字符串
     */
    public static String generateLowercase(int length) {
        return generate(length, true, false, true);
    }

    /**
     * 自定义生成随机字符串
     * @param length 字符串长度
     * @param includeDigits 是否包含数字
     * @param includeUppercase 是否包含大写字母
     * @param includeLowercase 是否包含小写字母
     * @return 随机字符串
     */
    public static String generate(int length, 
                                 boolean includeDigits, 
                                 boolean includeUppercase, 
                                 boolean includeLowercase) {
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be positive");
        }

        StringBuilder charPool = new StringBuilder();
        if (includeDigits) {
            charPool.append(DIGITS);
        }
        if (includeUppercase) {
            charPool.append(UPPERCASE_LETTERS);
        }
        if (includeLowercase) {
            charPool.append(LOWERCASE_LETTERS);
        }

        if (charPool.length() == 0) {
            throw new IllegalArgumentException("At least one character set must be selected");
        }

        StringBuilder result = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(charPool.length());
            result.append(charPool.charAt(randomIndex));
        }

        return result.toString();
    }

}